package com.example.sse.controller;

import com.example.sse.model.RealtimeData;
import com.example.sse.service.ClusterCommunicationService;
import com.example.sse.service.SseConnectionManager;
import com.example.sse.util.MapUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * 测试控制器
 * 提供SSE功能测试接口
 */
@Slf4j
@RestController
@RequestMapping("/api/test")
@RequiredArgsConstructor
public class TestController {

    private final SseConnectionManager sseConnectionManager;
    private final ClusterCommunicationService clusterCommunicationService;

    /**
     * 广播测试消息
     * @param request 测试消息请求
     * @return 响应结果
     */
    @PostMapping("/broadcast")
    public ResponseEntity<Map<String, Object>> broadcastTestMessage(@RequestBody TestMessageRequest request) {
        try {
            // 创建实时数据对象
            RealtimeData data = new RealtimeData();
            data.setId(String.valueOf(System.currentTimeMillis()));
            data.setType(request.getType() != null ? request.getType() : "test");
            data.setContent(request.getMessage() != null ? request.getMessage() : "测试消息");
            data.setTimestamp(LocalDateTime.now());
            
            // 通过集群通信服务广播消息
            clusterCommunicationService.broadcastToCluster(data);
            
            Map<String, Object> result = MapUtils.of(
                "success", true,
                "message", "测试消息广播成功",
                "data", MapUtils.of(
                    "id", data.getId(),
                    "type", data.getType(),
                    "content", data.getContent(),
                    "timestamp", data.getTimestamp()
                )
            );
            
            log.info("广播测试消息成功: {} - {}", data.getType(), data.getContent());
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("广播测试消息失败", e);
            Map<String, Object> result = MapUtils.of(
                "success", false,
                "message", "广播失败: " + e.getMessage(),
                "timestamp", System.currentTimeMillis()
            );
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 触发心跳检测
     * @return 响应结果
     */
    @PostMapping("/heartbeat")
    public ResponseEntity<String> triggerHeartbeat() {
        try {
            // 创建心跳数据
            RealtimeData heartbeat = new RealtimeData();
            heartbeat.setId("heartbeat_" + System.currentTimeMillis());
            heartbeat.setType("heartbeat");
            heartbeat.setContent("系统心跳检测");
            heartbeat.setTimestamp(LocalDateTime.now());
            
            // 广播心跳消息
            clusterCommunicationService.broadcastToCluster(heartbeat);
            
            log.info("心跳检测触发成功");
            return ResponseEntity.ok("心跳检测已触发");
            
        } catch (Exception e) {
            log.error("心跳检测触发失败", e);
            return ResponseEntity.ok("心跳检测失败: " + e.getMessage());
        }
    }

    /**
     * 获取测试统计信息
     * @return 统计信息
     */
    @GetMapping("/stats")
    public ResponseEntity<Map<String, Object>> getTestStats() {
        Map<String, Object> stats = MapUtils.of(
            "activeConnections", sseConnectionManager.getActiveConnectionCount(),
            "nodeId", sseConnectionManager.getNodeId(),
            "clusterInfo", clusterCommunicationService.getClusterNodeInfo(),
            "serverTime", System.currentTimeMillis(),
            "uptime", System.currentTimeMillis() // 简化的运行时间
        );
        
        return ResponseEntity.ok(stats);
    }

    /**
     * 获取监控指标
     * @return 监控指标
     */
    @GetMapping("/monitor/metrics")
    public ResponseEntity<Map<String, Object>> getMonitorMetrics() {
        Map<String, Object> metrics = MapUtils.of(
            "activeConnections", sseConnectionManager.getActiveConnectionCount(),
            "totalMessages", 0, // 这里可以添加消息计数逻辑
            "clusterNodes", 1, // 简化的集群节点数
            "uptime", System.currentTimeMillis(),
            "nodeId", sseConnectionManager.getNodeId()
        );
        
        return ResponseEntity.ok(metrics);
    }

    /**
     * 测试消息请求模型
     */
    public static class TestMessageRequest {
        private String type;
        private String message;
        private String timestamp;

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }

        public String getTimestamp() {
            return timestamp;
        }

        public void setTimestamp(String timestamp) {
            this.timestamp = timestamp;
        }
    }
}